package com.dlnaplayer;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * DLNA播放器模块
 */
@ReactModule(name = DlnaPlayerModule.NAME)
public class DlnaPlayerModule extends ReactContextBaseJavaModule {
    public static final String NAME = "DlnaPlayer";
    private static final String TAG = "DlnaPlayerModule";

    // 事件名称
    private static final String EVENT_DEVICE_FOUND = "deviceFound";
    private static final String EVENT_DEVICE_LOST = "deviceLost";
    private static final String EVENT_PLAYBACK_STATUS_CHANGED = "playbackStatusChanged";
    private static final String EVENT_CONNECTION_STATUS_CHANGED = "connectionStatusChanged";
    private static final String EVENT_ERROR_OCCURRED = "errorOccurred";

    // DLNA服务管理器
    private DlnaServiceManager dlnaServiceManager;
    
    // 设备列表
    private List<Map<String, Object>> deviceList;
    
    // 当前连接的设备
    private String currentDeviceId;
    
    // 当前播放的URL
    private String currentVideoUrl;
    
    // 播放状态监控器
    private Handler playbackMonitorHandler;
    private Runnable playbackMonitorRunnable;
    private boolean isMonitoringPlayback = false;

    public DlnaPlayerModule(ReactApplicationContext reactContext) {
        super(reactContext);
        
        // 初始化DLNA服务管理器
        initDlnaServiceManager();
        
        // 初始化设备列表
        deviceList = new ArrayList<>();
        
        // 初始化播放状态监控器
        playbackMonitorHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    @NonNull
    public String getName() {
        return NAME;
    }

    /**
     * 发送设备事件到JS
     */
    private void sendDeviceEvent(String eventName, Map<String, Object> device) {
        ReactApplicationContext context = getReactApplicationContext();
        if (context != null) {
            WritableMap params = new WritableNativeMap();
            
            params.putString("id", (String) device.get("id"));
            params.putString("name", (String) device.get("name"));
            params.putString("ipAddress", (String) device.get("ipAddress"));
            params.putString("type", "dlna");
            
            if (device.containsKey("model")) {
                params.putString("model", (String) device.get("model"));
            }
            
            if (device.containsKey("manufacturer")) {
                params.putString("manufacturer", (String) device.get("manufacturer"));
            }
            
            context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
        }
    }
    
    /**
     * 发送播放状态事件到JS
     */
    private void sendPlaybackStatusEvent(Map<String, Object> status) {
        ReactApplicationContext context = getReactApplicationContext();
        if (context != null) {
            WritableMap params = new WritableNativeMap();
            
            params.putBoolean("isPlaying", (Boolean) status.getOrDefault("isPlaying", false));
            params.putDouble("position", ((Long) status.getOrDefault("position", 0L)) / 1000.0);
            params.putDouble("duration", ((Long) status.getOrDefault("duration", 0L)) / 1000.0);
            params.putBoolean("isBuffering", (Boolean) status.getOrDefault("isBuffering", false));
            params.putBoolean("isCompleted", (Boolean) status.getOrDefault("isCompleted", false));
            params.putBoolean("isError", (Boolean) status.getOrDefault("isError", false));
            
            if (status.containsKey("errorMessage")) {
                params.putString("errorMessage", (String) status.get("errorMessage"));
            }
            
            context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(EVENT_PLAYBACK_STATUS_CHANGED, params);
        }
    }
    
    /**
     * 创建标准化错误对象
     * @param code 错误代码
     * @param message 错误消息
     * @param details 错误详情
     * @return 标准化错误对象
     */
    private WritableMap createError(String code, String message, @Nullable WritableMap details) {
        WritableMap error = new WritableNativeMap();
        error.putString("code", code);
        error.putString("message", message);
        
        if (details != null) {
            error.putMap("details", details);
        }
        
        return error;
    }

    /**
     * 发送错误事件
     * @param code 错误代码
     * @param message 错误消息
     * @param details 错误详情
     */
    private void sendErrorEvent(String code, String message, @Nullable WritableMap details) {
        WritableMap event = createError(code, message, details);
        sendEvent(EVENT_ERROR_OCCURRED, event);
    }

    /**
     * 拒绝Promise并发送错误事件
     * @param promise Promise对象
     * @param code 错误代码
     * @param message 错误消息
     * @param details 错误详情
     */
    private void rejectWithError(Promise promise, String code, String message, @Nullable WritableMap details) {
        WritableMap error = createError(code, message, details);
        
        // 发送错误事件
        sendEvent(EVENT_ERROR_OCCURRED, error);
        
        // 拒绝Promise
        promise.reject(code, message, new Exception(message));
    }

    /**
     * 将异常转换为标准化错误对象
     * @param e 异常
     * @param defaultCode 默认错误代码
     * @param defaultMessage 默认错误消息
     * @return 标准化错误对象
     */
    private WritableMap exceptionToError(Exception e, String defaultCode, String defaultMessage) {
        String code = defaultCode;
        String message = e.getMessage();
        
        if (message == null || message.isEmpty()) {
            message = defaultMessage;
        }
        
        WritableMap details = new WritableNativeMap();
        details.putString("stackTrace", Log.getStackTraceString(e));
        
        return createError(code, message, details);
    }
    
    /**
     * 开始监控播放状态
     */
    private void startPlaybackMonitoring() {
        if (isMonitoringPlayback) {
            return;
        }
        
        isMonitoringPlayback = true;
        
        if (playbackMonitorRunnable == null) {
            playbackMonitorRunnable = new Runnable() {
                @Override
                public void run() {
                    if (currentDeviceId != null && currentVideoUrl != null) {
                        try {
                            Map<String, Object> status = dlnaServiceManager.getPlaybackStatus(currentDeviceId);
                            sendPlaybackStatusEvent(status);
                        } catch (Exception e) {
                            Log.e(TAG, "Error monitoring playback: " + e.getMessage());
                        }
                    }
                    
                    if (isMonitoringPlayback) {
                        playbackMonitorHandler.postDelayed(this, 1000); // 每秒更新一次
                    }
                }
            };
        }
        
        playbackMonitorHandler.post(playbackMonitorRunnable);
    }
    
    /**
     * 停止监控播放状态
     */
    private void stopPlaybackMonitoring() {
        if (playbackMonitorHandler != null) {
            playbackMonitorHandler.removeCallbacksAndMessages(null);
            playbackMonitorHandler = null;
        }
    }

    /**
     * 搜索设备
     * @param timeout 超时时间（毫秒），0表示使用默认值
     * @param clearExisting 是否清除现有设备列表
     * @param promise 回调
     */
    @ReactMethod
    public void searchDevicesEnhanced(int timeout, boolean clearExisting, Promise promise) {
        if (!ensureDlnaServiceManager()) {
            promise.reject("MANAGER_ERROR", "DLNA服务管理器初始化失败");
            return;
        }
        
        try {
            // 使用增强的搜索功能
            if (clearExisting) {
                dlnaServiceManager.clearDevices();
            }
            
            final long searchTimeout = timeout > 0 ? timeout : 10000; // 默认10秒
            
            // 添加超时处理
            final Handler timeoutHandler = new Handler(Looper.getMainLooper());
            final AtomicBoolean isCompleted = new AtomicBoolean(false);
            
            // 超时任务
            final Runnable timeoutRunnable = new Runnable() {
                @Override
                public void run() {
                    if (isCompleted.compareAndSet(false, true)) {
                        // 如果超时仍未完成，返回当前已发现的设备
                        Log.w(TAG, "搜索设备超时，返回当前已发现设备");
                        List<Map<String, Object>> devices = dlnaServiceManager.getDevices();
                        WritableArray result = convertDevicesToWritableArray(devices);
                        promise.resolve(result);
                    }
                }
            };
            
            // 设置搜索超时
            timeoutHandler.postDelayed(timeoutRunnable, searchTimeout);
            
            // 在后台线程执行搜索
            new Thread(() -> {
                try {
                    // 使用带超时的搜索
                    dlnaServiceManager.searchWithTimeout(searchTimeout - 1000); // 稍微提前结束搜索
                    
                    // 等待一段时间让设备被发现
                    Thread.sleep(5000);
                    
                    if (isCompleted.compareAndSet(false, true)) {
                        // 正常完成，取消超时任务
                        timeoutHandler.removeCallbacks(timeoutRunnable);
                        
                        List<Map<String, Object>> devices = dlnaServiceManager.getDevices();
                        WritableArray result = convertDevicesToWritableArray(devices);
                        
                        // 启用自动重新搜索
                        dlnaServiceManager.setAutoResearch(true);
                        
                        promise.resolve(result);
                    }
                } catch (Exception e) {
                    if (isCompleted.compareAndSet(false, true)) {
                        // 发生异常，取消超时任务
                        timeoutHandler.removeCallbacks(timeoutRunnable);
                        
                        // 发送错误事件
                        sendErrorEvent("SEARCH_ERROR", "搜索设备失败: " + e.getMessage(), null);
                        
                        promise.reject("SEARCH_ERROR", "搜索设备失败: " + e.getMessage());
                    }
                }
            }).start();
        } catch (Exception e) {
            // 发送错误事件
            sendErrorEvent("SEARCH_ERROR", "搜索设备失败: " + e.getMessage(), null);
            
            promise.reject("SEARCH_ERROR", "搜索设备失败: " + e.getMessage());
        }
    }

    /**
     * 连接设备
     * @param deviceId 设备ID
     * @param promise 回调
     */
    @ReactMethod
    public void connectToDevice(String deviceId, Promise promise) {
        try {
            boolean result = dlnaServiceManager.connect(deviceId);
            if (result) {
                currentDeviceId = deviceId;
                
                // 发送连接状态变更事件
                WritableMap params = new WritableNativeMap();
                params.putString("deviceId", deviceId);
                params.putBoolean("connected", true);
                getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                    .emit(EVENT_CONNECTION_STATUS_CHANGED, params);
            }
            promise.resolve(result);
        } catch (Exception e) {
            // 发送错误事件
            sendErrorEvent("CONNECT_ERROR", "连接设备失败: " + e.getMessage(), null);
            
            promise.reject("CONNECT_ERROR", "连接设备失败: " + e.getMessage());
        }
    }

    /**
     * 断开设备连接
     * @param promise 回调
     */
    @ReactMethod
    public void disconnectFromDevice(Promise promise) {
        try {
            if (currentDeviceId != null) {
                boolean result = dlnaServiceManager.disconnect(currentDeviceId);
                if (result) {
                    // 停止播放状态监控
                    stopPlaybackMonitoring();
                    
                    // 发送连接状态变更事件
                    WritableMap params = new WritableNativeMap();
                    params.putString("deviceId", currentDeviceId);
                    params.putBoolean("connected", false);
                    getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                        .emit(EVENT_CONNECTION_STATUS_CHANGED, params);
                    
                    currentDeviceId = null;
                    currentVideoUrl = null;
                }
                promise.resolve(result);
            } else {
                promise.resolve(true);
            }
        } catch (Exception e) {
            // 发送错误事件
            sendErrorEvent("DISCONNECT_ERROR", "断开设备连接失败: " + e.getMessage(), null);
            
            promise.reject("DISCONNECT_ERROR", "断开设备连接失败: " + e.getMessage());
        }
    }

    /**
     * 播放视频（使用重试功能）
     * @param url 视频URL
     * @param title 视频标题
     * @param subtitle 视频副标题
     * @param coverUrl 封面URL
     * @param promise 回调
     */
    @ReactMethod
    public void playVideoWithRetry(String url, @Nullable String title, @Nullable String subtitle, @Nullable String coverUrl, Promise promise) {
        if (!ensureDlnaServiceManager()) {
            promise.reject("MANAGER_ERROR", "DLNA服务管理器初始化失败");
            return;
        }
        
        try {
            if (currentDeviceId == null) {
                // 发送错误事件
                sendErrorEvent("PLAY_ERROR", "未连接设备", null);
                
                promise.reject("PLAY_ERROR", "未连接设备");
                return;
            }
            
            // 使用带重试的播放方法
            boolean result = dlnaServiceManager.playWithRetry(currentDeviceId, url, title, subtitle, coverUrl);
            if (result) {
                currentVideoUrl = url;
                
                // 开始播放状态监控
                startPlaybackMonitoring();
            }
            promise.resolve(result);
        } catch (Exception e) {
            // 发送错误事件
            sendErrorEvent("PLAY_ERROR", "播放视频失败: " + e.getMessage(), null);
            
            promise.reject("PLAY_ERROR", "播放视频失败: " + e.getMessage());
        }
    }

    /**
     * 暂停播放（使用重试功能）
     * @param promise 回调
     */
    @ReactMethod
    public void pauseVideoWithRetry(Promise promise) {
        if (!ensureDlnaServiceManager()) {
            promise.reject("MANAGER_ERROR", "DLNA服务管理器初始化失败");
            return;
        }
        
        try {
            if (currentDeviceId == null || currentVideoUrl == null) {
                promise.reject("PAUSE_ERROR", "未连接设备或未播放视频");
                return;
            }
            
            // 使用带重试的暂停方法
            boolean result = dlnaServiceManager.pauseWithRetry(currentDeviceId);
            promise.resolve(result);
        } catch (Exception e) {
            promise.reject("PAUSE_ERROR", "暂停播放失败: " + e.getMessage());
        }
    }

    /**
     * 恢复播放（使用重试功能）
     * @param promise 回调
     */
    @ReactMethod
    public void resumeVideoWithRetry(Promise promise) {
        if (!ensureDlnaServiceManager()) {
            promise.reject("MANAGER_ERROR", "DLNA服务管理器初始化失败");
            return;
        }
        
        try {
            if (currentDeviceId == null || currentVideoUrl == null) {
                promise.reject("RESUME_ERROR", "未连接设备或未播放视频");
                return;
            }
            
            // 使用带重试的恢复播放方法
            boolean result = dlnaServiceManager.resumeWithRetry(currentDeviceId);
            promise.resolve(result);
        } catch (Exception e) {
            promise.reject("RESUME_ERROR", "恢复播放失败: " + e.getMessage());
        }
    }

    /**
     * 停止播放（使用重试功能）
     * @param promise 回调
     */
    @ReactMethod
    public void stopVideoWithRetry(Promise promise) {
        if (!ensureDlnaServiceManager()) {
            promise.reject("MANAGER_ERROR", "DLNA服务管理器初始化失败");
            return;
        }
        
        try {
            if (currentDeviceId == null || currentVideoUrl == null) {
                promise.reject("STOP_ERROR", "未连接设备或未播放视频");
                return;
            }
            
            // 使用带重试的停止播放方法
            boolean result = dlnaServiceManager.stopWithRetry(currentDeviceId);
            if (result) {
                currentVideoUrl = null;
            }
            promise.resolve(result);
        } catch (Exception e) {
            promise.reject("STOP_ERROR", "停止播放失败: " + e.getMessage());
        }
    }

    /**
     * 跳转到指定位置
     * @param position 位置（秒）
     * @param promise 回调
     */
    @ReactMethod
    public void seekTo(double position, Promise promise) {
        try {
            if (currentDeviceId == null || currentVideoUrl == null) {
                promise.reject("SEEK_ERROR", "未连接设备或未播放视频");
                return;
            }
            
            boolean result = dlnaServiceManager.seekTo(currentDeviceId, (long) (position * 1000));
            promise.resolve(result);
        } catch (Exception e) {
            promise.reject("SEEK_ERROR", "跳转失败: " + e.getMessage());
        }
    }

    /**
     * 获取播放状态
     * @param promise 回调
     */
    @ReactMethod
    public void getPlaybackStatus(Promise promise) {
        try {
            if (currentDeviceId == null) {
                promise.reject("STATUS_ERROR", "未连接设备");
                return;
            }
            
            Map<String, Object> status = dlnaServiceManager.getPlaybackStatus(currentDeviceId);
            WritableMap result = new WritableNativeMap();
            
            result.putBoolean("isPlaying", (Boolean) status.getOrDefault("isPlaying", false));
            result.putDouble("position", ((Long) status.getOrDefault("position", 0L)) / 1000.0);
            result.putDouble("duration", ((Long) status.getOrDefault("duration", 0L)) / 1000.0);
            result.putBoolean("isBuffering", (Boolean) status.getOrDefault("isBuffering", false));
            result.putBoolean("isCompleted", (Boolean) status.getOrDefault("isCompleted", false));
            result.putBoolean("isError", (Boolean) status.getOrDefault("isError", false));
            
            if (status.containsKey("errorMessage")) {
                result.putString("errorMessage", (String) status.get("errorMessage"));
            }
            
            promise.resolve(result);
        } catch (Exception e) {
            promise.reject("STATUS_ERROR", "获取播放状态失败: " + e.getMessage());
        }
    }

    /**
     * 设置音量
     * @param volume 音量（0-100）
     * @param promise 回调
     */
    @ReactMethod
    public void setVolume(double volume, Promise promise) {
        try {
            if (currentDeviceId == null) {
                promise.reject("VOLUME_ERROR", "未连接设备");
                return;
            }
            
            boolean result = dlnaServiceManager.setVolume(currentDeviceId, (int) volume);
            promise.resolve(result);
        } catch (Exception e) {
            promise.reject("VOLUME_ERROR", "设置音量失败: " + e.getMessage());
        }
    }

    /**
     * 获取音量
     * @param promise 回调
     */
    @ReactMethod
    public void getVolume(Promise promise) {
        try {
            if (currentDeviceId == null) {
                promise.reject("VOLUME_ERROR", "未连接设备");
                return;
            }
            
            int volume = dlnaServiceManager.getVolume(currentDeviceId);
            promise.resolve(volume);
        } catch (Exception e) {
            promise.reject("VOLUME_ERROR", "获取音量失败: " + e.getMessage());
        }
    }

    /**
     * 设置静音
     * @param mute 是否静音
     * @param promise 回调
     */
    @ReactMethod
    public void setMute(boolean mute, Promise promise) {
        try {
            if (currentDeviceId == null) {
                promise.reject("MUTE_ERROR", "未连接设备");
                return;
            }
            
            boolean result = dlnaServiceManager.setMute(currentDeviceId, mute);
            promise.resolve(result);
        } catch (Exception e) {
            promise.reject("MUTE_ERROR", "设置静音失败: " + e.getMessage());
        }
    }

    /**
     * 获取静音状态
     * @param promise 回调
     */
    @ReactMethod
    public void getMute(Promise promise) {
        try {
            if (currentDeviceId == null) {
                promise.reject("MUTE_ERROR", "未连接设备");
                return;
            }
            
            boolean mute = dlnaServiceManager.getMute(currentDeviceId);
            promise.resolve(mute);
        } catch (Exception e) {
            promise.reject("MUTE_ERROR", "获取静音状态失败: " + e.getMessage());
        }
    }

    /**
     * 将设备列表转换为WritableArray
     * @param devices 设备列表
     * @return WritableArray
     */
    private WritableArray convertDevicesToWritableArray(List<Map<String, Object>> devices) {
        WritableArray array = new WritableNativeArray();
        
        for (Map<String, Object> device : devices) {
            WritableMap map = new WritableNativeMap();
            
            map.putString("id", (String) device.get("id"));
            map.putString("name", (String) device.get("name"));
            map.putString("ipAddress", (String) device.get("ipAddress"));
            map.putString("type", "dlna");
            
            if (device.containsKey("model")) {
                map.putString("model", (String) device.get("model"));
            }
            
            if (device.containsKey("manufacturer")) {
                map.putString("manufacturer", (String) device.get("manufacturer"));
            }
            
            array.pushMap(map);
        }
        
        return array;
    }

    /**
     * 检查权限
     */
    @ReactMethod
    public void checkPermissions(Promise promise) {
        ReactApplicationContext context = getReactApplicationContext();
        if (context == null) {
            WritableMap result = new WritableNativeMap();
            result.putBoolean("hasPermissions", false);
            result.putString("errorMessage", "React应用上下文为空");
            promise.resolve(result);
            return;
        }

        // 创建返回结果
        WritableMap result = new WritableNativeMap();
        boolean hasAllPermissions = true;
        WritableArray missingPermissions = new WritableNativeArray();

        // 需要检查的权限
        String[] permissions = {
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.CHANGE_WIFI_MULTICAST_STATE
        };

        // 检查每个权限
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                hasAllPermissions = false;
                missingPermissions.pushString(permission);
            }
        }

        // 设置结果
        result.putBoolean("hasPermissions", hasAllPermissions);
        if (!hasAllPermissions) {
            result.putArray("missingPermissions", missingPermissions);
        }

        promise.resolve(result);
    }

    /**
     * 检查单个权限状态
     */
    @ReactMethod
    public void checkSinglePermission(String permissionName, Promise promise) {
        ReactApplicationContext context = getReactApplicationContext();
        if (context == null) {
            promise.reject("E_CONTEXT_UNAVAILABLE", "React应用上下文不可用");
            return;
        }
        
        // 将权限类型转换为实际的Android权限
        String permission = getAndroidPermission(permissionName);
        if (permission == null) {
            // 如果不是Android权限，返回GRANTED
            promise.resolve("GRANTED");
            return;
        }
        
        // 检查权限状态
        int permissionStatus = ContextCompat.checkSelfPermission(context, permission);
        if (permissionStatus == PackageManager.PERMISSION_GRANTED) {
            promise.resolve("GRANTED");
        } else {
            // 检查是否应该显示权限请求理由
            boolean shouldShowRationale = false;
            Activity activity = getCurrentActivity();
            if (activity != null) {
                shouldShowRationale = ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
            }
            
            if (shouldShowRationale) {
                promise.resolve("DENIED");
            } else {
                // 如果不应该显示理由，可能是首次请求或用户选择了"不再询问"
                promise.resolve("PERMANENTLY_DENIED");
            }
        }
    }

    /**
     * 显示权限请求理由
     */
    @ReactMethod
    public void showPermissionRationale(String permissionName, String rationale, Promise promise) {
        Activity activity = getCurrentActivity();
        if (activity == null) {
            promise.reject("E_ACTIVITY_DOES_NOT_EXIST", "Activity不存在，无法显示权限请求理由");
            return;
        }
        
        // 在UI线程上显示对话框
        activity.runOnUiThread(() -> {
            new AlertDialog.Builder(activity)
                .setTitle("需要" + permissionName + "权限")
                .setMessage(rationale)
                .setPositiveButton("确定", (dialog, which) -> {
                    promise.resolve(true);
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    promise.resolve(false);
                })
                .show();
        });
    }

    /**
     * 检查权限的永久拒绝状态
     */
    @ReactMethod
    public void checkPermanentlyDeniedPermissionStatus(Promise promise) {
        Activity activity = getCurrentActivity();
        if (activity == null) {
            promise.reject("E_ACTIVITY_DOES_NOT_EXIST", "Activity不存在，无法检查权限");
            return;
        }
        
        // 需要检查的权限
        String[] permissions = {
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.CHANGE_WIFI_MULTICAST_STATE
        };
        
        WritableMap result = new WritableNativeMap();
        WritableArray permanentlyDeniedPermissions = new WritableNativeArray();
        boolean hasPermanentlyDeniedPermissions = false;
        
        for (String permission : permissions) {
            int permissionStatus = ContextCompat.checkSelfPermission(activity, permission);
            if (permissionStatus != PackageManager.PERMISSION_GRANTED) {
                boolean shouldShowRationale = ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
                if (!shouldShowRationale) {
                    // 如果权限被拒绝且不应该显示请求理由，就认为被永久拒绝了
                    permanentlyDeniedPermissions.pushString(permission);
                    hasPermanentlyDeniedPermissions = true;
                }
            }
        }
        
        result.putBoolean("hasPermanentlyDeniedPermissions", hasPermanentlyDeniedPermissions);
        if (hasPermanentlyDeniedPermissions) {
            result.putArray("permanentlyDeniedPermissions", permanentlyDeniedPermissions);
        }
        
        promise.resolve(result);
    }

    /**
     * 重置权限请求历史记录
     */
    @ReactMethod
    public void resetPermissionRequestHistory(Promise promise) {
        // Android不需要实际实现此方法，因为权限请求历史是由系统管理的
        // 但为了API一致性，我们提供一个空实现
        promise.resolve(true);
    }

    /**
     * 获取所需的权限信息列表
     */
    @ReactMethod
    public void getRequiredPermissions(Promise promise) {
        WritableArray permissions = new WritableNativeArray();
        
        // 添加INTERNET权限信息
        WritableMap internetPermission = new WritableNativeMap();
        internetPermission.putString("type", "INTERNET");
        internetPermission.putString("name", "网络访问");
        internetPermission.putString("description", "允许应用程序连接到互联网");
        internetPermission.putString("rationale", "DLNA播放器需要访问网络以发现设备并传输媒体内容。");
        internetPermission.putBoolean("isRequired", true);
        permissions.pushMap(internetPermission);
        
        // 添加ACCESS_NETWORK_STATE权限信息
        WritableMap networkStatePermission = new WritableNativeMap();
        networkStatePermission.putString("type", "NETWORK_STATE");
        networkStatePermission.putString("name", "网络状态");
        networkStatePermission.putString("description", "允许应用程序访问有关网络的信息");
        networkStatePermission.putString("rationale", "DLNA播放器需要检测当前的网络连接状态以确保设备可以正常通信。");
        networkStatePermission.putBoolean("isRequired", true);
        permissions.pushMap(networkStatePermission);
        
        // 添加ACCESS_WIFI_STATE权限信息
        WritableMap wifiStatePermission = new WritableNativeMap();
        wifiStatePermission.putString("type", "WIFI_STATE");
        wifiStatePermission.putString("name", "WiFi状态");
        wifiStatePermission.putString("description", "允许应用程序访问有关WiFi网络的信息");
        wifiStatePermission.putString("rationale", "DLNA播放器需要检测WiFi网络状态以确保设备在同一网络中。");
        wifiStatePermission.putBoolean("isRequired", true);
        permissions.pushMap(wifiStatePermission);
        
        // 添加CHANGE_WIFI_MULTICAST_STATE权限信息
        WritableMap wifiMulticastPermission = new WritableNativeMap();
        wifiMulticastPermission.putString("type", "WIFI_MULTICAST");
        wifiMulticastPermission.putString("name", "WiFi多播");
        wifiMulticastPermission.putString("description", "允许应用程序接收所有多播包");
        wifiMulticastPermission.putString("rationale", "DLNA设备发现需要使用多播协议，这是发现本地网络上的设备所必需的。");
        wifiMulticastPermission.putBoolean("isRequired", true);
        permissions.pushMap(wifiMulticastPermission);
        
        promise.resolve(permissions);
    }

    /**
     * 将权限类型转换为Android权限
     */
    private String getAndroidPermission(String permissionType) {
        switch (permissionType) {
            case "INTERNET":
                return Manifest.permission.INTERNET;
            case "NETWORK_STATE":
                return Manifest.permission.ACCESS_NETWORK_STATE;
            case "WIFI_STATE":
                return Manifest.permission.ACCESS_WIFI_STATE;
            case "WIFI_MULTICAST":
                return Manifest.permission.CHANGE_WIFI_MULTICAST_STATE;
            case "LOCAL_NETWORK":
                // Android没有直接对应的本地网络权限
                return null;
            default:
                return null;
        }
    }

    /**
     * React Native模块销毁时调用
     * 用于清理资源，防止内存泄漏
     */
    @Override
    public void invalidate() {
        // 清理DLNA服务管理器资源
        if (dlnaServiceManager != null) {
            try {
                // 停止搜索
                dlnaServiceManager.stopSearch();
                
                // 断开当前连接
                if (currentDeviceId != null) {
                    dlnaServiceManager.disconnect(currentDeviceId);
                    currentDeviceId = null;
                }
                
                // 释放资源
                dlnaServiceManager.release();
                dlnaServiceManager = null;
                
                Log.d(TAG, "DLNA服务管理器资源已释放");
            } catch (Exception e) {
                Log.e(TAG, "释放DLNA服务管理器资源时出错: " + e.getMessage());
            }
        }
        
        // 停止播放状态监控
        stopPlaybackMonitoring();
        
        // 清理其他资源
        deviceList.clear();
        
        super.invalidate();
    }

    /**
     * 初始化DLNA服务管理器
     */
    private void initDlnaServiceManager() {
        if (dlnaServiceManager == null) {
            try {
                Log.d(TAG, "开始初始化DLNA服务管理器...");
                
                // 检查权限
                boolean hasPermissions = checkRequiredPermissions();
                if (!hasPermissions) {
                    Log.e(TAG, "初始化DLNA服务管理器失败: 缺少必要的权限");
                    return;
                }
                
                dlnaServiceManager = new DlnaServiceManager(getReactApplicationContext()) {
                    @Override
                    protected void onDeviceAdded(Map<String, Object> device) {
                        // 在主线程处理设备添加
                        new Handler(Looper.getMainLooper()).post(() -> handleDeviceAdded(device));
                    }
                    
                    @Override
                    protected void onDeviceRemoved(Map<String, Object> device) {
                        // 在主线程处理设备移除
                        new Handler(Looper.getMainLooper()).post(() -> handleDeviceRemoved(device));
                    }
                };
                
                Log.d(TAG, "DLNA服务管理器初始化成功");
            } catch (Exception e) {
                Log.e(TAG, "初始化DLNA服务管理器失败: " + e.getMessage(), e);
            }
        }
    }
    
    /**
     * 检查必要的权限
     */
    private boolean checkRequiredPermissions() {
        Context context = getReactApplicationContext();
        if (context == null) {
            Log.e(TAG, "React应用上下文为空");
            return false;
        }
        
        String[] permissions = {
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.CHANGE_WIFI_MULTICAST_STATE
        };
        
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "缺少权限: " + permission);
                return false;
            }
        }
        
        return true;
    }

    /**
     * 确保DLNA服务管理器可用
     * 如果已被释放，则重新初始化
     */
    private boolean ensureDlnaServiceManager() {
        if (dlnaServiceManager == null) {
            Log.d(TAG, "DLNA服务管理器未初始化，尝试初始化...");
            initDlnaServiceManager();
        }
        
        if (dlnaServiceManager == null) {
            Log.e(TAG, "DLNA服务管理器初始化失败");
            return false;
        }
        
        return true;
    }

    /**
     * 处理设备添加事件
     */
    private void handleDeviceAdded(Map<String, Object> device) {
        // 向JS发送设备添加事件
        sendDeviceEvent(EVENT_DEVICE_FOUND, device);
        
        // 更新设备列表
        synchronized (deviceList) {
            // 检查设备是否已存在
            String deviceId = (String) device.get("id");
            boolean exists = false;
            
            for (int i = 0; i < deviceList.size(); i++) {
                Map<String, Object> existingDevice = deviceList.get(i);
                if (deviceId.equals(existingDevice.get("id"))) {
                    // 更新现有设备
                    deviceList.set(i, device);
                    exists = true;
                    break;
                }
            }
            
            // 如果不存在，添加到列表
            if (!exists) {
                deviceList.add(device);
            }
        }
    }

    /**
     * 处理设备移除事件
     */
    private void handleDeviceRemoved(Map<String, Object> device) {
        // 向JS发送设备移除事件
        sendDeviceEvent(EVENT_DEVICE_LOST, device);
        
        // 从设备列表中移除
        synchronized (deviceList) {
            String deviceId = (String) device.get("id");
            
            for (int i = 0; i < deviceList.size(); i++) {
                Map<String, Object> existingDevice = deviceList.get(i);
                if (deviceId.equals(existingDevice.get("id"))) {
                    deviceList.remove(i);
                    break;
                }
            }
        }
    }

    /**
     * 发送事件到JS
     * @param eventName 事件名称
     * @param params 事件参数
     */
    private void sendEvent(String eventName, @Nullable WritableMap params) {
        ReactApplicationContext context = getReactApplicationContext();
        if (context != null && context.hasActiveReactInstance()) {
            context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
        } else {
            Log.w(TAG, "无法发送事件 " + eventName + "，React上下文不可用或无活动实例");
        }
    }

    /**
     * 搜索设备（兼容原始API）
     * @param promise 回调
     */
    @ReactMethod
    public void searchDevices(Promise promise) {
        // 使用增强版本，默认超时10秒，不清除现有设备
        searchDevicesEnhanced(10000, false, promise);
    }
    
    /**
     * 播放视频（兼容原始API）
     * @param url 视频URL
     * @param title 视频标题
     * @param subtitle 视频副标题
     * @param coverUrl 封面URL
     * @param promise 回调
     */
    @ReactMethod
    public void playVideo(String url, @Nullable String title, @Nullable String subtitle, @Nullable String coverUrl, Promise promise) {
        playVideoWithRetry(url, title, subtitle, coverUrl, promise);
    }
    
    /**
     * 暂停播放（兼容原始API）
     * @param promise 回调
     */
    @ReactMethod
    public void pauseVideo(Promise promise) {
        pauseVideoWithRetry(promise);
    }
    
    /**
     * 恢复播放（兼容原始API）
     * @param promise 回调
     */
    @ReactMethod
    public void resumeVideo(Promise promise) {
        resumeVideoWithRetry(promise);
    }
    
    /**
     * 停止播放（兼容原始API）
     * @param promise 回调
     */
    @ReactMethod
    public void stopVideo(Promise promise) {
        stopVideoWithRetry(promise);
    }

    /**
     * 停止搜索设备
     * @param promise 回调
     */
    @ReactMethod
    public void stopScan(Promise promise) {
        try {
            if (!ensureDlnaServiceManager()) {
                promise.reject("ERROR", "DLNA服务管理器未初始化");
                return;
            }
            
            dlnaServiceManager.stopSearch();
            promise.resolve(true);
        } catch (Exception e) {
            Log.e(TAG, "停止搜索设备失败: " + e.getMessage());
            promise.reject("ERROR", e.getMessage());
        }
    }

    /**
     * 开始搜索设备
     * @param promise 回调
     */
    @ReactMethod
    public void startScan(Promise promise) {
        try {
            if (!ensureDlnaServiceManager()) {
                promise.reject("ERROR", "DLNA服务管理器未初始化");
                return;
            }
            
            dlnaServiceManager.search();
            promise.resolve(true);
        } catch (Exception e) {
            Log.e(TAG, "开始搜索设备失败: " + e.getMessage());
            promise.reject("ERROR", e.getMessage());
        }
    }
} 